<?php

class FrontController {
	protected $_controller;
	protected $_action;
	public $_params;
	protected $_body;
	static $BaseUrl;
	public $modules_dir = array(
		'default' => '',
		'admin' => ''
	);
	public $module = 'default';
	static $_instance;
	
	public static function getInstance(){
		if(!(self::$_instance instanceof self)){
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	private function __construct(){
		if(!defined('APP_DIR')){
			throw new Exception('not found APP_DIR in FrontController');
			exit();
		}
		$this->module = 'default';
		$this->modules_dir = array(
			'default'=>APP_DIR.'/controllers/default',
			'admin'=>APP_DIR.'/controllers/admin'
		);
		$request = $_SERVER['REQUEST_URI'];
		if(strstr($request,'/')==0){
			$request = substr($request,1);
		}
		$splits = explode('/',trim($request));
		if(empty($splits[0])){
			$this->_controller = 'Index';
			$this->_action = 'index';
			$this->module = 'default';
			$i = 0;
		}else if(array_key_exists($splits[0],$this->modules_dir)){
			$this->_controller = empty($splits[1]) ? 'Index' : ucfirst($splits[1]);
			$this->_action = empty($splits[2]) ? 'index' : $splits[2];
			$this->module = $splits[0];
			$i = 3;
		}else{
			$this->_controller = ucfirst($splits[0]);
			$this->_action = empty($splits[1]) ? 'index' : $splits[1];
			$this->module = 'default';
			$i = 2;
		}
		if($i != 0){
			$keys = $values = array();
			for($idx = $i; $idx < count($splits); $idx ++){
				$split = explode('-',$splits[$idx]);
				if(empty($split[0])){
					continue;
				}
				$keys[] = $split[0];
				$values[] = $split[1];		
			}
			$this->_params = array_combine($keys, $values);
		}
		//echo $this->_controller;exit;
		//echo $this->_action;exit;
	}
	
	public function route(){
		if(file_exists($this->modules_dir[$this->module].'/'.$this->_controller.'Controller.php')){
			require_once($this->modules_dir[$this->module].'/'.$this->_controller.'Controller.php');
			if(class_exists($this->_controller.'Controller')){
				$rc = new ReflectionClass($this->_controller.'Controller');
				if($rc->isSubclassOf('BaseController')){
					if($rc->hasMethod($this->_action.'Action')){
						$controller = $rc->newInstance();
						$method = $rc->getMethod($this->_action.'Action');
						$method->invoke($controller);
					}else{
						throw new Exception($this->_action.':this action not found');
					}
				}else{
					throw new Exception('not found Interface'.PHP_EOL);
				}
			}else{
				throw new Exception($this->_controller.':this controller not found');
			}
			
		}else{
			throw new Exception('this controller file not found:'.$this->_controller.'Controller.php');
		}
		
	}
	
	public function setBaseUrl($baseurl){
		self::$BaseUrl = $baseurl;
	}
	
	function addModule($module,$module_dir){
		$this->module = $module;
		$this->modules_dir[$module] = $module_dir;
	}
	
	function setModule($module){
		$this->module = $module;
	}
}

?>